package com.mustafaiev.tair.mlauncher;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

/**
 * Connectivity manager
 * 
 * @author Tair Mustafaiev
 * 
 */
public class MLauncherConnectivityManager {

	private static final String SET_MOBILE_DATA_ENABLED = "setMobileDataEnabled";
	private final Context context;

	public MLauncherConnectivityManager(final Context context) {
		this.context = context;
	}

	/**
	 * Changes mobile data state e.g. enables or disables the mobile data.
	 * 
	 * @param <code>boolean</code> isEnabled
	 */
	@SuppressWarnings({ "rawtypes" })
	public void setMobileDataEnabled(final boolean isEnabled) {

		try {
			final ConnectivityManager cm = (ConnectivityManager) this.context
					.getSystemService(Context.CONNECTIVITY_SERVICE);

			final Class connectivityManager = Class.forName(cm.getClass()
					.getName());

			final Method[] methods = connectivityManager.getDeclaredMethods();

			for (final Method method : methods) {
				if (MLauncherConnectivityManager.SET_MOBILE_DATA_ENABLED
						.equals(method.getName())) {
					Log.i(method.getName() + " invoking", method.getName());
					method.invoke(cm, isEnabled);
				}
			}

		} catch (final ClassNotFoundException e) {
			Log.e("LauncherConnectivityManager.setMobileDataEnabled(final boolean isEnabled) ",
					e.getMessage());
		} catch (final IllegalArgumentException e) {
			Log.e("LauncherConnectivityManager.setMobileDataEnabled(final boolean isEnabled) ",
					e.getMessage());
		} catch (final IllegalAccessException e) {
			Log.e("LauncherConnectivityManager.setMobileDataEnabled(final boolean isEnabled) ",
					e.getMessage());
		} catch (final InvocationTargetException e) {
			Log.e("LauncherConnectivityManager.setMobileDataEnabled(final boolean isEnabled) ",
					e.getMessage());
		}
	}

	/**
	 * Checks whether mobile data is enabled or disabled. If it's enabled than
	 * return <code>true</code> otherwise <code>false</code>;
	 * 
	 * @return <code>boolean true</code> or <code>false</code>
	 */
	public boolean isMobileDataEnabled() {

		final ConnectivityManager connManager = (ConnectivityManager) this.context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		final NetworkInfo networkInfo = connManager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		if (networkInfo.isConnectedOrConnecting()) {
			Log.i("MLauncherActivity.isMobileDataEnabled()",
					"Mobile data is enabled");
			return true;
		} else {
			Log.i("MLauncherActivity.isMobileDataEnabled()",
					"Mobile data is disabled");
			return false;
		}
	}
}
